使用map能直接用索引來比對,這題有點階梯感(? 比如說你跨上一個階梯後,要往下踩一格踏踏看有沒有穩,才能繼續往上踩(雖然很抽象,但我腦袋就浮出這些東西><)
class Solution {
public:
static bool cmp(const string &s1, const string &s2){
return s1.length() < s2.length();
}
int longestStrChain(vector<string>& words) {
sort(words.begin(), words.end(), cmp);
unordered_map<string, int> ump;
int ans = 0;
for(string w : words){
int longest = 0;
for(int i = 0; i < w.length(); i++){
string sub = w;
sub.erase(i, 1);
longest = max(longest, ump[sub] + 1);
}
ump[w] = longest;
ans = max(ans, longest);
}
return ans;
}
};